<?php

Class Infopark
{
    
   #var $test=123; 
    var $cities_list;
    var $current_city;
    var $current_city_tid;
    var $categories_names;
    var $category_list;
    var $all_events;
    //buffer for _front_get_event_days
    var $days;
    //buffer for places
    var $all_places;
    var $memcache;
    var $sambanners;
    var $sambanners_frequency;
    var $sambanners_count;
    var $md_slider_count;
    function Infopark()
    {
        $this->memcache=new Memcache;
        $this->memcache->connect('localhost', 11211) or die ("Не могу подключиться");
        $this->md_slider_count=0;
        //init session
         #echo function_exists('geoip_country_code');
        #$smart_ip_session = smart_ip_session_get('smart_ip'); 
       # pre($smart_ip_session);
       
        //$this->memcache = new Memcache;
        //$this->memcache->connect('localhost', 11211) or die ("MEMCACHE said: Не могу подключиться");

        
    }
    /*function detect_geoip_city()
    {
      #
       
             $ip=geoip_ip_address();
             $city=geoip_city($ip);
            # echo $ip."<hr>";
           
         $t=db_select("citydomain","c")->fields("c")->condition('name_en',$city->city)->execute()->fetchAssoc();
             if($t['tid'])
             {
                 $current_tid=$this->get_city_tid;
                if((!isset($_SESSION['current_tid'])&&($current_tid!=$t['tid'])))
                {
                    
                    $_SESSION['current_tid']=$t['tid'];
                    drupal_goto($t['url']);
                }
               
             }else{
                 #pre($city);
                 
             }
            #  die("<hr>");
#.geoip_country_code($ip).
     #  pre();
        
    }*/
    function get_sambanners()
    {
        $current_city=$this->get_city_by_url();
        
       # pre($current_city);
       //$query=db_select('sambanners','s');
      $query=db_select('sambanners','s');
               $query->leftJoin('sambanners_index','i','i.sid=s.id');
               $query->fields("s");
               if($current_city['tid'])
               {
                   $query->condition('i.tid',$current_city['tid']);
                   
               }				$query->DISTINCT();
              $query->condition('s.status',1)
              ->orderBy('s.ord','DESC');
  
       
    $result=$query->execute();
    while($r=$result->fetchObject())
    {
        $banners[]=$r;
    }#if($_SERVER['REMOTE_ADDR']=='5.29.34.66')pre($banners);
    return $banners;
    }
    function mget($key)
    {
        $res=unserialize($this->memcache->get($key));
        if(($res['time']+3600)<time())
        return false;
        else return $res['object'];
     
    }
    function mset($key,$obj)
    {
     $data['object']=$obj;
    $data['time']=time();
    $this->memcache->set($key, serialize($data));
    }
    function mflush()
    {
     $this->memcache->flush();   
    }
    function draw_dm($date)
    {
        global $conf;
        $t=strtotime($date);
        return date('j',$t).' '.$conf['month_names'][date('n',$t)-1];
    }
    function draw_event_time($time,$showtime=true)
    {
        global $conf;
       $html='<div class="eventdate">';
       $html.='<div class="event_dw"><span class="event_d">'.date('j',$time).'</span> <span class="event_w">'.$conf['week_days_short'][date('w',$time)]."</span></div>";
       $html.='<div class="event_m">'.$conf['month_names'][date('n',$time)-1]."</div>";
       if($showtime)$html.='<div class="event_time">'.date('H:i',$time)."</div>";
       return $html;
       $html='</div>';
       // $date.' '.$conf['month_names'][date('n',strtotime($e->field_schedule_start_value))-1]."/".$conf['week_days_short'][date('w',strtotime($e->field_schedule_start_value))];

    }
     function draw_my($date)
    {
        global $conf;
        $t=strtotime($date);
        return $conf['month_namez'][date('n',$t)-1]." ".date('Y',$t);
    }
    function _spec_events_category_list($nid=0)
    {
        if($nid)
        {
         if($this->category_list[$nid])return $this->category_list[$nid];
        }else{
         if($this->category_list)return $this->category_list;   
        }
            
       # 
        
            $query = db_select('node', 'n');
            $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');

            $query->fields('n', array('nid'))
                      ->fields('ti', array('tid'))
                    ->condition('n.type', 'event');
            if($nid)
            {
            $query->condition('n.nid', $nid); 
           
           #
            }
            $result = $query->execute()->fetchAll();
            if($nid)
            {
               #@ print $nid;
               #   print $query;
               # pre($result);
            }
          #  $category_list = array();
            foreach ($result as $value) {
                    $this->category_list[$value->nid][] = $value->tid;
            }
            
            if($nid)return $this->category_list[$nid];
            else return $this->category_list;

    }
    function get_event_taxonomy()
    {
        if($this->categories_names)return $this->categories_names;
        foreach(taxonomy_get_tree(8) as $cc)$this->categories_names[$cc->tid]=$cc->name;
        return $this->categories_names;
    }
   function get_city_tid()
    {
       if($this->current_city_tid)return $this->current_city_tid; 
         $t=db_select("citydomain","c")->fields("c")->condition('url','http://'.$_SERVER['HTTP_HOST'])->execute()->fetchAssoc();
         if($t['tid'])
            {    
             $this->current_city_tid=$t['tid'];
            }else{
            $this->current_city_tid=0;
            }
            return $this->current_city_tid;
        
    }
    function get_city_by_url()
    {
        if($this->current_city)return $this->current_city;
        
        $t=db_select("citydomain","c")->fields("c")->condition('url','http://'.$_SERVER['HTTP_HOST'])->execute()->fetchAssoc();
        if($t['tid'])
        {    
	$current_city = 0;
	$current_city_name = "";
	$result = array ();
	$result['current_city'] = $t['tid'];
        $result['tid'] = $t['tid'];
	$result['current_city_name'] = $t['name'];
        $result['name'] = $t['name'];
        $this->current_city=$result;
	return $result;
        }else{
        return false;
        }
    }
    function cities_list()
    {
        if($this->cities_list)return $this->cities_list;
        
        $cities_rec=db_select("citydomain","c");
                $cities_rec->leftJoin("taxonomy_term_data","td","td.tid=c.tid");
                $cities_rec->fields("c")->orderBy("td.weight");
                $result=$cities_rec->execute();
	
	while($c=$result->fetchObject())
		{
		//$this->cities_list[$c->tid]=$c->name;
                $this->cities_list[$c->tid]=$c;
		}
		return $this->cities_list;
        
    }
    function get_statuses_from_tids($tids)
    {
        $statuses=array();
        foreach($tids as $tid)
        {
            if($tid==111)$statuses['recommended']=true;
            if($tid==157)$statuses['buytickets']=true;
            if($tid=='top')$statuses['top']=true;
             if($tid=='tour')$statuses['tour']=true;
        }
    
        return $statuses;
    }
    function clear_tids_from_statuses($tids)
    {
        $arr=array(111,157,'top','tour');
        $new_tids=false;
        foreach($tids as $tid)
        {
            if(!in_array($tid, $arr))$new_tids[]=$tid;
        }
    
     return $new_tids;
    }
    /*
     * GEt events by schedule nid
     */
    function _front_get_events($nids,$date)
    {
        $cc=$this->get_city_by_url();
        $current_city=$cc['tid'];
         $query = db_select('node', 'n');	
		$query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		$query->leftJoin('field_data_field_src', 'src', 'n.nid = src.entity_id');
		
		$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		$query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
		$query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
		#$query->leftJoin('taxonomy_index', 'ti', 'event_node.nid = ti.nid');
                $query->leftJoin('field_data_field_recommended', 'recom', 'event_node.nid = recom.entity_id');
		$query->leftJoin('field_data_field_event_buy_a_ticket', 'buy_ticket', 'event_node.nid = buy_ticket.entity_id');
		#$query->leftJoin('field_data_field_event_ticket_id', 'ticket_id', 'event_node.nid = ticket_id.entity_id');
                $query->leftJoin('field_data_field_tour', 'tour', 'event_node.nid = tour.entity_id');
		$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
		#$query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', event_node.nid)");

		$query->fields('event_node', array('title', 'nid','status'))
                #$query->fields('event_node', array('nid'));
                        ->fields('n', array('nid')) 
			->fields('s_start', array('field_schedule_start_value')) 
               # $query->addExpression('CONCAT(event_node.nid,\'\')','count_nid');
                #$query->addExpression('GROUP_CONCAT(DISTINCT event_node.nid SEPARATOR \',\')','nids');
                #$query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')','date');
              #  $query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
			->fields('f', array('uri'))
			#->fields('ua')
			->fields('place_city', array('field_place_city_tid'))
			->fields('s_place', array('field_schedule_place_nid'))
			->fields('src', array('field_src_value'))
			->fields('place_node', array('title'))
                       # ->fields('buy_ticket',array(''))
                        ->fields('recom',array('field_recommended_value'))
			->fields('event_desc',array('field_event_description_value'))
                        ->fields('tour',array('field_tour_value'));
                               
			#->fields('ti', array('tid'));

			#->groupBy('title')
			#$query->groupBy('s_start.field_schedule_start_value');
			//$query->groupBy('place_node.title');
			//$query->groupBy('s_start.field_schedule_start_value');
                        #$query->groupBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
			#$query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC')
			#->orderBy('(ti.tid=111)', 'DESC')
			$query->orderBy('recom.field_recommended_value', 'DESC')->orderBy('s_start.field_schedule_start_value', 'ASC')
			->condition('n.type', 'schedule');
			#$query->condition('event_node.status', 1);
			$query->condition('n.nid',explode(',',$nids),'IN');
			$query->condition('event_node.type', 'event');
			if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
			
			#$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') >= (:today)", array(':today' => date('Ymd')));
			$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') = (:date)", array(':date' => $date));
			#$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') IN (:dates)", array(':dates' => $dates));
                      #  $query->range(0,7);
			#print ($query);
			#dpm((string) $query);
			
	$events = $query->execute()->fetchAll();
        return $events;
    }        
    /*
     * GEt events schedule nids,count and date only first static load
     */
    function _front_get_event_days()
    {
        if($this->days)return $this->days;
        $cc=$this->get_city_by_url();
        $current_city=$cc['tid'];
        
        $query = db_select('node', 'n');	
		$query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		$query->leftJoin('field_data_field_src', 'src', 'n.nid = src.entity_id');
		
		$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		$query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
		$query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
		#$query->leftJoin('taxonomy_index', 'ti', 'event_node.nid = ti.nid');
		#$query->leftJoin('field_data_field_event_buy_a_ticket', 'buy_ticket', 'event_node.nid = buy_ticket.entity_id');
                
		#$query->leftJoin('field_data_field_event_ticket_id', 'ticket_id', 'event_node.nid = ticket_id.entity_id');
		$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
		#$query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', event_node.nid)");

		//$query->fields('event_node', array('title', 'nid','status'))
                #$query->fields('event_node', array('nid'));
		#	->fields('s_start', array('field_schedule_start_value')) 
               # $query->addExpression('CONCAT(event_node.nid,\'\')','count_nid');
                $query->addExpression('GROUP_CONCAT(DISTINCT n.nid SEPARATOR \',\')','nids');
               #// $query->addExpression('GROUP_CONCAT(DISTINCT event_node.nid SEPARATOR \',\')','nids');
                $query->addExpression('COUNT(event_node.nid)','events_count');
                $query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')','date');
              #  $query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
			//->fields('f', array('uri'))
			#->fields('ua')
			//->fields('place_city', array('field_place_city_tid'))
			//->fields('s_place', array('field_schedule_place_nid'))
			//->fields('src', array('field_src_value'))
			//->fields('place_node', array('title'))
		
			//->fields('event_desc',array('field_event_description_value'))
                               
			#->fields('ti', array('tid'));

			#->groupBy('title')
			#$query->groupBy('s_start.field_schedule_start_value');
			//$query->groupBy('place_node.title');
			//$query->groupBy('s_start.field_schedule_start_value');
                        $query->groupBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
			$query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC')
			#->orderBy('(ti.tid=111)', 'DESC')
			->orderBy('s_start.field_schedule_start_value', 'ASC')
			->condition('n.type', 'schedule');
			#$query->condition('event_node.status', 1);
	#		
			$query->condition('event_node.type', 'event');
			if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
			
			$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') >= (:today)", array(':today' => date('Ymd')));
			#$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') IN (:dates)", array(':dates' => $dates));
			#$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') IN (:dates)", array(':dates' => $dates));
                        $query->range(0,7);
			#print ($query);
			#dpm((string) $query);
			#pre($current_city);
	$days = $query->execute()->fetchAll();
       
        $this->days=$days;
        return $days;
    }
    function front_get_event_days_ajax($d,$type)
    {
        $cc=$this->get_city_by_url();
    #@   $cc =advert_compromise_get_citydomain($_SERVER['HTTP_HOST']);
    $current_city=$cc['tid'];
    
    $query = db_select('node', 'n');	
		$query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		$query->leftJoin('field_data_field_src', 'src', 'n.nid = src.entity_id');
		
		$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		$query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
		$query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
		$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
		
                $query->addExpression('GROUP_CONCAT(DISTINCT n.nid SEPARATOR \',\')','nids');
                $query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')','date');
                 $query->addExpression('COUNT(event_node.nid)','events_count');
                        $query->groupBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
			
			#->orderBy('(ti.tid=111)', 'DESC')
			#->orderBy('s_start.field_schedule_start_value', 'ASC')
			$query->condition('n.type', 'schedule');
			#$query->condition('event_node.status', 1);
	#		
			$query->condition('event_node.type', 'event');
			if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
	 $query->range(0,7);		
    if($type=='next')
    {
     
    $query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > (:today)", array(':today' => $d));
   $query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC');
     $days = $query->execute()->fetchAll();
    }else{
        $query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') < (:day)", array(':day' => $d));
        $query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') >= (:today)", array(':today' => date('Ymd')));
    $query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'DESC'); 
       $days = $query->execute()->fetchAll();
       $days=array_reverse($days);
    } 
    return $days;
    }
    function rebuild_days($days)
    {
        foreach($days as $d)
        {
            $events=$this->_front_get_events($d->nids,$d->date);
            #pre($events);
           $this->all_events[$d->date]=$events;
        }
        return $this->all_events;
    }
    function rebuild_days_place($days)
    {
        foreach($days as $d)
        {
            $places=$this->_front_get_places($d->nids,$d->date);
           $this->all_places[$d->date]=$places;
            #$events=$this->_front_get_events($d->nids,$d->date);
            #pre($events);
           $this->all_events[$d->date]=$events;
        }
        return $this->all_places;
    }
    /**
 * Block Afishes on FrontPage
 * **/
function _front_events_affishes($days)
{

     $out='';
        $first=1;
       # $all_events[]=array();
        foreach($days as $d=>$v)
        {
            /*$events=$this->_front_get_events($d->nids,$d->date);
            #pre($events);
           $this->all_events[$d->date]=$events;*/
         
            $out.='
                <div class="front_events_box box_'.$d.'">'.$this->_front_draw_events($v).'</div>';
            $first=0;
            
        }      
        return $out;
        #$out.='</ul>';
    #urn '<div style="border:solid black 1px;">Events<br>'.$out.'</div>';
    
}
function _front_draw_events($events)
{
    
    $out='<Table>
            <Tr><td><span class="prev_event_lnk" onclick="prev_event();"></span></td>
            <td rowspan=2 class="affishe_box"><ul>';
       foreach($events as $event)
       {
       $out.='<li class="bbox'.$event->n_nid.'"><div class="pin">'.$this->_spec_event_front($event).'</div></li>';
       }
       $out.='</ul></td>
           <td><span onclick="next_event();" class="next_event_lnk"></span></td></tr>
</table>';
   return $out;
}
function _front_places_affishes($days)
{

     $out='';
        $first=1;
       # $all_events[]=array();
        foreach($days as $d=>$v)
        {
           # $places=$this->_front_get_places($v->nids,$dv->date);
          # $this->all_places[$d->date]=$places;
         
            $out.='
                <div class="front_places_box box_'.$d.'">'.$this->_front_draw_places($v).'</div>';
            $first=0;
            
        }      
        return $out;
        #$out.='</ul>';
    #urn '<div style="border:solid black 1px;">Events<br>'.$out.'</div>';
    
}
function _front_draw_places($places)
{
    global $infopark;
     $out='<Table>
            <Tr><td><span class="prev_place_lnk" onclick="prev_place();"></span></td>
            <td rowspan="2"><ul>';
       foreach($places as $p)
       {
       $out.='<li class="bboxplace'.$p->n_nid.'">'.$infopark->_front_draw_place($p).'</li>';
       }
       $out.='</ul></td><td><span onclick="next_place();" class="next_place_lnk"></span></td></tr>
</table>';
   return $out;
   /*
    $out='<div class="columns">';
    foreach($places as $p)
    {
        $out.=$infopark->_front_draw_place($p);
    }
    $out.='</div>';
    return $out;*/
}
function _front_draw_events_list($days)
{
    global $conf;
    $out='<div class="front_events_list"><ul>';
    
   foreach($days as $day=>$events)
   {
       #$out.='<ul class="list_'.$day.'">';
      $out.='<li class="list_'.$day.' date"><h5 onclick="sw_event_date(\''.$day.'\')">'.$this->draw_dm($day).' / '.$conf['week_days_short'][date('w',  strtotime($day))].'</h5></li>';
       $ind=0;
       foreach($events as $event)
       {
          #pre($event);
           
           $out.='<li class="list_'.$day.' llist'.$event->n_nid.'" onclick="sw2affishe('.$day.','.$event->n_nid.','.$ind.')">
               <table>
                    <tr>
                        <td class="front_list_time">'.date('H:i',strtotime($event->field_schedule_start_value)). '</td><td class="front_list_title">'.$event->title.'</td>';
           if($event->field_recommended_value)
           {
               $out.='<td class="list_recomend">Рекомендуем</td>';
           }
           $out.='</tr></table></li>';
         $ind++;       
       }
       #$out.='</ul>';
   }
   $out.='</ul>';
   for($i=0;$i<25;$i++)
   {
       $out.='<br>';
   }
    $out.='</div>';
    return $out;
}

function _front_draw_places_list($days)
{
    global $conf;
    $out='<div class="front_places_list"><ul>';
   
   foreach($days as $day=>$places)
   {
       $out.='<li class="listplaces_'.$day.' date"><h5 onclick="sw_place_date(\''.$day.'\')">'.$this->draw_dm($day).' / '.$conf['week_days_short'][date('w',  strtotime($day))].'</h5></li>';  
      # $out.='<ul class="listplaces_'.$day.'">';
       $ind=0;
       foreach($places as $p)
       {
         #$p->title.'" в '.
      
           $out.='<li class="listplaces_'.$day.' llistplaces'.$p->n_nid.'" onclick="sw2affishe_places('.$day.','.$p->n_nid.','.$ind.')">
                   <table>
                    <tr>
                        <td class="front_list_time">'.date('H:i',strtotime($p->field_schedule_start_value)).' - "'.$p->place_node_title.'</td></tr></table></li>';
         $ind++;       
       }
       #$out.='</ul>';
   }
    $out.='</ul>';
       for($i=0;$i<25;$i++)
   {
       $out.='<br>';
   }
    $out.='</div>';
    return $out;
}
function _front_get_places($nids,$date)
{
     $cc=$this->get_city_by_url();
        $current_city=$cc['tid'];
         $query = db_select('node', 'n');	
		$query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		//$query->leftJoin('field_data_field_src', 'src', 'n.nid = src.entity_id');
		
		$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		$query->leftJoin('field_revision_field_place_thumbnail', 'pthumbnail', 'place_node.nid = pthumbnail.entity_id');
                $query->leftJoin('file_managed', 'pfm', 'pfm.fid = pthumbnail.field_place_thumbnail_fid');
                
                $query->leftJoin('field_revision_field_place_address','p_address','p_address.entity_id=place_node.nid');
		$query->leftJoin('field_revision_field_place_phone','p_phone','p_phone.entity_id=place_node.nid');
		$query->leftJoin('field_revision_field_place_website','p_web','p_web.entity_id=place_node.nid');
                
                $query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
		$query->leftJoin('citydomain', 'cd', 'cd.tid = place_city.field_place_city_tid');
                $query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
		#$query->leftJoin('taxonomy_index', 'ti', 'event_node.nid = ti.nid');
                $query->leftJoin('field_data_field_recommended', 'recom', 'event_node.nid = recom.entity_id');
		$query->leftJoin('field_data_field_event_buy_a_ticket', 'buy_ticket', 'event_node.nid = buy_ticket.entity_id');
		#$query->leftJoin('field_data_field_event_ticket_id', 'ticket_id', 'event_node.nid = ticket_id.entity_id');
		$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
		#$query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', event_node.nid)");

		$query->fields('event_node', array('title', 'nid','status'))
                        ->fields('n', array('nid')) 
                #$query->fields('event_node', array('nid'));
			->fields('s_start', array('field_schedule_start_value')) 
               # $query->addExpression('CONCAT(event_node.nid,\'\')','count_nid');
                #$query->addExpression('GROUP_CONCAT(DISTINCT event_node.nid SEPARATOR \',\')','nids');
                #$query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')','date');
              #  $query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
			->fields('f', array('uri'))
			#->fields('ua')
			->fields('place_city', array('field_place_city_tid'));
                       # ->fields('cd', array('city_name'=>'name','city_url'=>'url'))
                      $query->addField('cd', 'name', 'city_name');
                       $query->addField('cd', 'url', 'city_url');
                       $query->addField('pfm', 'uri', 'pfm_image');
                        $query->addField('p_address', 'field_place_address_value', 'p_address');
                        $query->addField('p_phone', 'field_place_phone_value', 'p_phone');
                        $query->addField('p_web', 'field_place_website_value', 'p_web');
                   #     ->fields('cd', array('url'),'city_url')
			$query->fields('s_place', array('field_schedule_place_nid'))
			//->fields('src', array('field_src_value'))
			->fields('place_node', array('title'))
                       # ->fields('buy_ticket',array(''))
                        ->fields('recom',array('field_recommended_value'))
			->fields('event_desc',array('field_event_description_value'));
                               
			#->fields('ti', array('tid'));

			#->groupBy('title')
			#$query->groupBy('s_start.field_schedule_start_value');
			//$query->groupBy('place_node.title');
			//$query->groupBy('s_start.field_schedule_start_value');
                        #$query->groupBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
			#$query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC')
			#->orderBy('(ti.tid=111)', 'DESC')
			$query->orderBy('recom.field_recommended_value', 'DESC')->orderBy('s_start.field_schedule_start_value', 'ASC')
			->condition('n.type', 'schedule');
			#$query->condition('event_node.status', 1);
			$query->condition('n.nid',explode(',',$nids),'IN');
			$query->condition('event_node.type', 'event');
                        $query->condition('s_place.field_schedule_place_nid',0,'<>');
			if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
			
			#$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') >= (:today)", array(':today' => date('Ymd')));
			$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') = (:date)", array(':date' => $date));
                        
			#$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') IN (:dates)", array(':dates' => $dates));
                        $query->range(0,8);
			#print ($query);
			#dpm((string) $query);
			
    $places = $query->execute()->fetchAll();
    //pre($places);
    return $places;
}
function _front_draw_place($p)
{

    $img=(!empty($p->pfm_image)?$p->pfm_image:$p->uri);

    #print image_style_url('w220',$p->pfm_image);
    $out='<div class="pin">
'.l('<div class="thumb">'.theme_image(array('path'=>image_style_url('w220',$img))).'</div>','node/'.$p->field_schedule_place_nid,array('html'=>true))
 .'<div class="info">'
            . '<h2>'.l($p->place_node_title,'node/'.$p->field_schedule_place_nid).'</h2>

<table class="short_info"><tbody><tr>
<td class="short_info_label"><div class="icon city"></div> </td>
<td><a class="city_link" href="'.$p->city_url.'"> '.$p->city_name.'</a></td></tr>
<tr><td class="short_info_label"></td><td>'.$p->p_address.'</td></tr>
<tr><td><div class="icon phone"></div></td><td>'.$p->p_phone.'</td></tr>
</tbody></table></div>
<div class="order_tickets_lnk_inline">'.l('<span class="more">Подробнее</span>','node/'.$p->field_schedule_place_nid,array('html'=>true,'attributes'=>array('title'=>$p->place_node_title,'rel'=>'nofollow'))).'
</div>
							
</div>';
 return $out;
}
/**
 * FROM EVENTS CALENDAR
 */
function _front_events_cal($days)
{
    $out='<ul class="front_events_dates">
            <li class="front_date_arrows_prev"  onclick="sw_li_period('.$days[0]->date.',\'prev\')"><div></div></li>';
        global $conf;
        $first=1;
        foreach($days as $d)
        {
          
            
            
            
            $t=strtotime($d->date);
            $out.='<li class="date_'.$d->date.($first?' active_li_date':'').'" onclick="sw_event_date('.$d->date.')"><div class="lidate"><div class="event_date">'.date('j',$t).' <font'.((date('w',$t)==0)?' class="holiday"':'').'>'.$conf['week_days_short'][date('w',$t)].'</font></div> '.$conf['month_names'][date('n',$t)-1]
                    .'<div class="event_counter" title="Количество событий">'.$d->events_count.'</div></div></li>';
            $first=0;
            
        }   
        $out.='<li class="front_date_arrows_next" onclick="sw_li_period('.$d->date.',\'next\')"><div></div></li></ul>';
 return $out;
}
/**
 * FROM PLACES CALENDAR
 */
function _front_places_cal($days)
{
    $out='<ul class="front_places_dates">
            <li class="front_date_arrows_prev"  onclick="sw_li_period_places('.$days[0]->date.',\'prev\')"><div></div></li>';
        global $conf;
        $first=1;
        foreach($days as $d)
        {  
          
            $t=strtotime($d->date);
            $out.='<li class="dateplaces_'.$d->date.($first?' active_li_date_places':'').'" onclick="sw_place_date('.$d->date.')"><div class="event_date">'.date('j',$t).' <font'.((date('w',$t)==0)?' color="red"':'').'>'.$conf['week_days_short'][date('w',$t)].'</font> </div> '.$conf['month_names'][date('n',$t)-1]
                    .'<br>'
                    .'<div class="event_counter" title="Количество событий">'.$d->events_count.'</div></li>';
            $first=0;
            
        }   
        $out.='<li class="front_date_arrows_next" onclick="sw_li_period_places('.$d->date.',\'next\')"><div></div></li></ul>';
 return $out;
}
function get_other_events_w_ticket($nid,$tid)
{
    $cc=$this->get_city_by_url();
        $current_city=$cc['tid'];
    $query = db_select('node', 'n');	
		$query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		$query->leftJoin('field_data_field_src', 'src', 'n.nid = src.entity_id');
		
		$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		$query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
		$query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
		$query->leftJoin('taxonomy_index', 'ti', 'event_node.nid = ti.nid');
                $query->leftJoin('taxonomy_index', 'ti2', 'event_node.nid = ti2.nid');
                $query->leftJoin('field_data_field_tour', 'tour', 'event_node.nid = tour.entity_id');
                $query->leftJoin('field_data_field_recommended', 'recom', 'event_node.nid = recom.entity_id');
		$query->leftJoin('field_data_field_event_buy_a_ticket', 'buy_ticket', 'event_node.nid = buy_ticket.entity_id');
		$query->leftJoin('field_data_field_event_ticket_id', 'ticket_id', 'event_node.nid = ticket_id.entity_id');
		$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
		$query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', event_node.nid)");

		$query->fields('event_node', array('title', 'nid','status'))

			->fields('s_start', array('field_schedule_start_value'))
			->fields('f', array('uri'))
			->fields('ua')
			->fields('place_city', array('field_place_city_tid'))
			->fields('s_place', array('field_schedule_place_nid'))
			->fields('src', array('field_src_value'))
			->fields('place_node', array('title'))
			->fields('buy_ticket', array('field_event_buy_a_ticket_value'))
                        ->fields('recom', array('field_recommended_value'))
			->fields('ticket_id', array('field_event_ticket_id_value'))
			->fields('event_desc',array('field_event_description_value'))
                        ->fields('s_event',array('entity_id'))
                         ->fields('tour',array('field_tour_value'))
			->fields('ti', array('tid'))->fields('ti2', array('tid'));

			#->groupBy('title')
			#$query->groupBy('s_start.field_schedule_start_value');
			$query->groupBy('place_node.title');
			$query->groupBy('s_start.field_schedule_start_value');
			#$query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC')
			$query->orderBy('recom.field_recommended_value', 'DESC')
			->orderBy('s_start.field_schedule_start_value', 'ASC')
			->condition('n.type', 'schedule');
			#if(user_access('administer nodes')==0)$query->condition('event_node.status', 1);
	#		
			$query->condition('event_node.type', 'event');
                          $query->condition('event_node.nid',$nid,'!=');
			if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
			
			#$query->condition('ti.tid',array(157,$term['taxonomy_term']->tid),'IN');
			$query->condition('ti.tid',157);
                        $query->condition('ti2.tid',$tid);
			$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > (:date)", array(':date' => date('Ymd')));
			#$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') IN (:dates)", array(':dates' => $dates));
			  $query->range(0,3);
			#dpm((string) $query);
			#pre($current_city);
                $others = $query->execute()->fetchAll();
                return $others;
}
function get_events($tids,$statuses,$dates)
{
   
$cc=$this->get_city_by_url();
$current_city=$cc['tid'];
$query = db_select('node', 'n');	
		$query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		$query->leftJoin('field_data_field_src', 'src', 'n.nid = src.entity_id');
		
		$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		$query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
		$query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
		$query->leftJoin('taxonomy_index', 'ti', 'event_node.nid = ti.nid');
		$query->leftJoin('field_data_field_event_buy_a_ticket', 'buy_ticket', 'event_node.nid = buy_ticket.entity_id');
                
                $query->leftJoin('field_data_field_recommended', 'recom', 'event_node.nid = recom.entity_id');
                
                if($statuses['top']) $query->leftJoin('field_data_field_top', 'top', 'event_node.nid = top.entity_id');
               $query->leftJoin('field_data_field_tour', 'tour', 'event_node.nid = tour.entity_id');
                  
		$query->leftJoin('field_data_field_event_ticket_id', 'ticket_id', 'event_node.nid = ticket_id.entity_id');
		$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
	#	$query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', event_node.nid)");

		$query->fields('event_node', array('title', 'nid','status'))

			->fields('s_start', array('field_schedule_start_value'))
			->fields('f', array('uri'))
			->fields('s_event',array('entity_id'))
			->fields('place_city', array('field_place_city_tid'))
			->fields('s_place', array('field_schedule_place_nid'))
			->fields('src', array('field_src_value'))
			->fields('place_node', array('title'))
			->fields('buy_ticket', array('field_event_buy_a_ticket_value'))
                        ->fields('recom', array('field_recommended_value'))
			->fields('ticket_id', array('field_event_ticket_id_value'))
			->fields('event_desc',array('field_event_description_value'))
                        ->fields('tour',array('field_tour_value'));
			#->fields('ti', array('tid'));

			#->groupBy('title')
			#$query->groupBy('s_start.field_schedule_start_value');
			$query->groupBy('place_node.title');
			$query->groupBy('s_start.field_schedule_start_value');
			$query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC')
			->orderBy('recom.field_recommended_value', 'DESC')
                        #->orderBy('(ti.tid=111)', 'DESC')
			->orderBy('s_start.field_schedule_start_value', 'ASC')
			->condition('n.type', 'schedule');
			if(user_access('administer nodes')==0)$query->condition('event_node.status', 1);
			
			$query->condition('event_node.type', 'event');
			if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
			
			if($tids)$query->condition('ti.tid',$tids,'IN');
			if($statuses['recommended'])$query->condition('recom.field_recommended_value',1);
                    
                        if($statuses['buytickets'])
                            {
                            $query->condition('buy_ticket.field_event_buy_a_ticket_value',1);
                         #   print ($query);
                            }
                      
                        if(user_access('administer nodes'))
                        {
                             if($statuses['top']) $query->condition('top.field_top_value',1);
                            if($statuses['tour']) $query->condition('tour.field_tour_value',1);
                        }
                   #     
			$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') IN (:dates)", array(':dates' => $dates));
			#$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') IN (:dates)", array(':dates' => $dates));
			
			#dpm((string) $query);
			#pre($current_city);
	$events = $query->execute()->fetchAll();
        return $events;
}
function sambanner_init()
{
    $this->sambanners=$this->get_sambanners();
     $this->sambanners_all=$this->sambanners;
    $this->sambanners_frequency=variable_get('sambanner_frequency',10);
    $this->sambanners_count=0;
}
function draw_events($events)
{
    global $conf;
        $out='';
	$old_day='';

        $cities_list=$this->cities_list();
       
        $this->sambanner_init();
       
        
	$c=0;

	foreach ($events as $e)
	{
        $e->is_recommended=$e->field_recommended_value;
       
        $key=date('d-m-Y',strtotime($e->field_schedule_start_value));
 
        if($e->is_recommended)$new_events[$key]['rec'][]=$e;
            else $new_events[$key]['reg'][]=$e;
            
            $rec_count=count($new_events[$key]['rec']);
            if(($rec_count>0)&&(isset($new_events[$key]['reg'])))
            {
                $ost=((ceil($rec_count/3)*3)-$rec_count);
               for($o=0;$o<$ost;$o++)
               {
                   $one=array_shift($new_events[$key]['reg']);
                  if(count($one))array_push($new_events[$key]['rec'],$one);
                  unset($one);
               
               }
             
            }
         
            
	$old_key=$key;
      
	}
	
        foreach($new_events as $the_day=>$day_events)
	{
	
	/*if(($f%2)>0){$out.='<div class="banner"><a href="http://radmir-expohall.com.ua/xarkov-beauty-3" target="_blank">
            <img src="/misc/images/banner.gif" width="630"></a></div>'."\n\n";}
	$f++;*/
	
       $t=strtotime($the_day);
        $out.='<div class="events_mid_day1"><span class="events_mid1">
            <div class="lnk_place_time">
            <a rel="nofollow" href="/events?day='.date('dmY',$t).'"></a>
            <div class="eventdate"><a rel="nofollow" href="/events?day='.date('dmY',$t).'">
            <div class="event_dw"><span class="event_d">'.date('d',$t).'</span> <span class="event_w">'.$conf['week_days_short'][date('w',$t)].'</span></div><div class="event_m">'.$conf['month_names'][date('n',$t)-1].'</div>
            </a></div></div>

           </span></div>'."\n\n";
	$out.='<div id="columns">'."\n\n";
if($day_events['rec'])
foreach ($day_events['rec'] as $e)
       {
        $time = substr($e->field_schedule_start_value, 10, 6); 
        $month = $month_names[(substr($e->field_schedule_start_value, 5, 2))-1];
        $day_of_month = substr($e->field_schedule_start_value, 8, 2);
        $out.='<div class="pin ';
                        if(user_access('administer nodes')&&($e->status==0))$out.='node_unactive';	


        $out.=" day_of_month_".$day_of_month." the_date_".str_replace('-','_',substr($e->field_schedule_start_value,0,10)).'">'."\n";

        $arg=array('e'=>$e,
                        'current_city'=>$current_city,
                        'categories_names'=>$categories_names,
                        'cities_list'=>$cities_list);				

        #$out.=_spec_event_recommended($arg);
        $out.=_spec_event($arg);
         
            $out.='</div>'."\n";
            if($this->sambanners_count==($this->sambanners_frequency-2))
                        {
                           $out.=$this->get_sambanner(); 
                           $this->sambanners_count=0;
                        }else
                        $this->sambanners_count++;
        }
	#$out.='</div>';
	#$out.='<div id="columns">'."\n\n";
    foreach ($day_events['reg'] as $e)
    {

       # if( ($current_city && $e->field_place_city_tid == $current_city ) || ($current_city == 0))
            #{

            $time = substr($e->field_schedule_start_value, 10, 6); 
            $month = $month_names[(substr($e->field_schedule_start_value, 5, 2))-1];
            $day_of_month = substr($e->field_schedule_start_value, 8, 2);

            $out.='<div class="pin ';
            if(user_access('administer nodes')&&($e->status==0))$out.='node_unactive';	

            $out.=" day_of_month_".$day_of_month." the_date_".str_replace('-','_',substr($e->field_schedule_start_value,0,10)).'">'."\n";
            #pre($e);
            $arg=array('e'=>$e,
                            'current_city'=>$current_city,
                            'categories_names'=>$categories_names,
                            'cities_list'=>$cities_list);				

            $out.=_spec_event($arg);

            $out.='</div>'."\n";
                        
              if($this->sambanners_count==($this->sambanners_frequency-2))
                        {
                           $out.=$this->get_sambanner(); 
                           $this->sambanners_count=0;
                        }else
                        $this->sambanners_count++;          
   # } //end if
    }
	$out.='</div>'."\n\n";
	}
return $out;
}
function get_sambanner()
{
   $banner=array_pop($this->sambanners);
   if(!isset($banner))
   {
       $this->sambanners=$this->sambanners_all;
       $banner=array_pop($this->sambanners);
   }
   if(isset($banner))
   {
 if($banner->code)
 {
     $html=$banner->code;
 }else{
     $html='<a href="'.$banner->link.'" target=_blank rel="nofollow"><img src="'.file_create_url($banner->img).'"></a>';
 }
 $html='<div class="pin adv">'.$html.'</div>';
return $html;
   }
    
}
function create_export_events_lnk()
{
    $main_url=$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	
        $export_menu='<h5>Выбирите формат файла:</h5>';
        $export_menu.='<ul>';
        $export_menu.='<li><a href=http://'.$main_url.'|export=xls>XLS</a></li>';
        $export_menu.='<li><a href=http://'.$main_url.'|export=xml>XML</a></li>';
        $export_menu.='</ul>';
        $out='<div class="export_lnk" style="text-align:right"><a href="javascript://" onclick="modal.open({content: \''.$export_menu.'\'});">Экспорт</a></div>';
return $out;      
}
/**
*Дизайн элемента событий,for frontpage
**/
function _spec_event_front($e)
{

global $conf,$infopark;

//extract($args);
$cities_list=$this->cities_list();
$current_city=$this->get_city_by_url();
$time = substr($e->field_schedule_start_value, 10, 6); 
$date=date('j',strtotime($e->field_schedule_start_value)).' '.$conf['month_names'][date('n',strtotime($e->field_schedule_start_value))-1]."/".$conf['week_days_short'][date('w',strtotime($e->field_schedule_start_value))];

#if($e->field_event_buy_a_ticket_value)

 $out='<div class="item_table">

                        <div class="event_thumb_info'.(($e->field_recommended_value)?' recomended':'').'">
                            <!--a href="'.$e->alias.'"-->';
                if(isset($e->field_src_value)&&(!empty($e->field_src_value)))
                {

                 $link.='<div class="thumb">'.($e->field_tour_value?'<div class="istour_front"></div>':'').'<img src="'.image_style_url('w220', substr($e->field_src_value,21)).'" alt="'.prep_text($e->title).'"></div>';
                }	
                    elseif (isset($e->uri))
                                {
$link.='<div class="thumb">'.($e->field_tour_value?'<div class="istour_front"></div>':'').'<img src="'.image_style_url('w220', $e->uri).'"  alt="'.prep_text($e->title).'"></div>';
                    }else{
$link.='<div class="thumb">'.($e->field_tour_value?'<div class="istour_front"></div>':'').'</div>';
                    }
                
            $out.=l($link,'node/'.$e->nid,array('html'=>true,'title'=>prep_text($e->title),'query'=>array('evt'=>$e->n_nid)));		
                          #  $out.='</a>';
	
                            $out.='<div class="info" id="info'.$e->nid.'">
                            
                                <h2>'.l($e->title, 'node/' . $e->nid,array('title'=>prep_text($e->title))).'</h2>';
					            $flag = 0;
								
								//$out.='<div class="event_excerpt">'._spec_event_prepare_text($e->field_event_description_value).'</div>	';

		                        $out.='<table class="short_info">';
		                        	$out.='<tr>';
		                         		$out.='<td class="short_info_label">';
		                             		$out.='<div class="icon datetime"></div>';
		                         		$out.='</td>';
		                         		$out.='<td>'.$time;
										
										$out.='</td>';
		                        	$out.='</tr>';
		                        	$out.='<tr>';
		                        		$out.='<td class="short_info_label">';
		                        			$out.='<div class="icon city"></div>';
		                        		$out.='</td>';
		                        		$out.='<td>';
							$out.=l($e->place_node_title, 'node/'  .  $e->field_schedule_place_nid);
									                                    
					if ($current_city == 0) {$out.='<div>'.$cities_list[$e->field_place_city_tid]->name.'</div>';}
		                        		
		                        		$out.='</td>';
		                        	$out.='</tr>';
		                        $out.='</table>';

						#if(($e->field_event_buy_a_ticket_value)&&(strtotime($e->field_schedule_start_value)>time()))
                                        
							$out.='<div class="order_tickets_lnk_inline_top">
									'.l('<span class="more">Подробнее</span>','node/'.$e->nid,array('html'=>true,'attributes'=>array('title'=>$e->title,'rel'=>'nofollow'))).'
									</div>';
							
				      
                        $out.='</div>
                </div>'."\n";
return $out;
}
function _front_get_gallery()
{
    $query = db_select('node', 'n');	
    $query->leftJoin('field_revision_media_gallery_media', 'frmgm', 'frmgm.entity_id=n.nid');
    $query->leftJoin('file_managed', 'fm', 'fm.fid=frmgm.media_gallery_media_fid');
    $query->fields('n',array('title','nid'));
    $query->fields('fm',array('fid','uri'));
    #$query->fields('fm');
    $query->condition('n.type','media_gallery');
    $query->condition('n.status',1);
    $query->condition('fm.status',1);
    $query->condition('fm.type','image');
    $query->orderBy('rand()');
    $query->range(0,7);
    $photos=$query->execute()->fetchAll();
  #  pre($photos);
    return $photos;
}
function get_place_by_event($event_id,$type)
{
    #print $event_id;
    $query=db_select('node','n');
    
    $query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.field_schedule_event_nid');
    $query->leftJoin('field_data_field_schedule_start', 's_start', 's_event.entity_id = s_start.entity_id');
    $query->leftJoin('field_data_field_schedule_place', 's_place', 's_event.entity_id = s_place.entity_id');
    $query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
    $query->condition('n.nid',$event_id);
    if($type=='past')
    {
        $query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') < (:date)", array(':date' => date('Ymd')));
       // $query->condition('s_start.field_schedule_start_value','')
    }
    
    $query->fields('place_node',array('nid','title'));
     $query->fields('s_start',array('field_schedule_start_value'));
    $places=$query->execute()->fetchAll();
    return $places;
}
function get_place_by_event2($event_id)
{
    #print $event_id;
    $query=db_select('node','n');
    
    $query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.field_schedule_event_nid');
    $query->leftJoin('field_data_field_schedule_start', 's_start', 's_event.entity_id = s_start.entity_id');
    $query->leftJoin('field_data_field_schedule_place', 's_place', 's_event.entity_id = s_place.entity_id');
    
    $query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
    $query->leftJoin('field_data_field_place_city', 's_city', 's_city.entity_id = place_node.nid');
    $query->leftJoin('taxonomy_term_data', 't', 't.tid = s_city.field_place_city_tid');
    $query->condition('n.nid',$event_id);
    
        $query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') >= (:date)", array(':date' => date('Ymd')));
       // $query->condition('s_start.field_schedule_start_value','')
    
    
    $query->fields('place_node',array('nid','title'));
    $query->fields('s_start',array('field_schedule_start_value'));
    # $query->fields('s_city');
    $query->fields('t',array('name'));
    $places=$query->execute()->fetchAll();
    return $places;
}
function split_events_by_my($events)
{
    foreach($events as $e)
    {
        $dm=$this->draw_my($e->field_schedule_start_value);
        $new_events[$dm][]=$e;
    }
    return $new_events;
}
function js_init_events($frag,$events)
{
    $out='<script>
        jQuery( document ).ready(function() {';
    foreach($events as $event)
    {
        if(isset($event->field_src_value)&&(!empty($event->field_src_value)))
            {
             $src=image_style_url('w220', substr($event->field_src_value,21));
            }else{
            $src=image_style_url('w220', $event->uri);
            }
        $out.='event_tooltip(".'.$frag.$event->nid.'","'.$src.'","");'."\n";
    }
     $out.='});</script>';
     return $out;
}

function get_top_events($limit,$range=0)
{
    $cc=$this->get_city_by_url();
$current_city=$cc['tid'];
    $query=  db_select('node','n');
  $query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		$query->leftJoin('field_data_field_src', 'src', 'n.nid = src.entity_id');
		
		$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		$query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
		$query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
                $query->leftJoin('field_revision_field_top', 'top', 'top.entity_id = event_node.nid');
                $query->leftJoin('field_data_field_tour', 'tour', 'tour.entity_id = event_node.nid');
                
		$query->leftJoin('taxonomy_index', 'ti', 'event_node.nid = ti.nid');
		$query->leftJoin('field_data_field_event_buy_a_ticket', 'buy_ticket', 'event_node.nid = buy_ticket.entity_id');
                
                $query->leftJoin('field_data_field_recommended', 'recom', 'event_node.nid = recom.entity_id');
		$query->leftJoin('field_data_field_event_ticket_id', 'ticket_id', 'event_node.nid = ticket_id.entity_id');
		$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
	

		$query->fields('event_node', array('title', 'nid','status'))

			#->fields('s_start', array('field_schedule_start_value'))
			->fields('f', array('uri'))
		
			#->fields('place_city', array('field_place_city_tid'))
			#->fields('s_place', array('field_schedule_place_nid'))
			#->fields('src', array('field_src_value'))
			#->fields('place_node', array('title'))
			#->fields('buy_ticket', array('field_event_buy_a_ticket_value'))
                        #->fields('recom', array('field_recommended_value'))
			
                        ->fields('tour', array('field_tour_value'))
			#->fields('event_desc',array('field_event_description_value'))
                                ;
	
			$query->groupBy('event_node.title');
		
			$query->orderBy('top.field_top_value', 'DESC')
                                ->orderBy('recom.field_recommended_value', 'DESC')
                                ->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC')
		
			->orderBy('s_start.field_schedule_start_value', 'ASC')
			->condition('n.type', 'schedule');
			$query->condition('event_node.status', 1);
                        $query->condition('top.field_top_value', 1);
			$query->condition('event_node.type', 'event');
			if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
			
			$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > (:date)", array(':date' => date('Ymd')));
		
                        $query->range($range,$limit);
	$events = $query->execute()->fetchAll();
      # pre($events);
        return $events;
}
function _front_top_event($e)
{
    if($e->field_tour_value)
    {
     $src=image_style_url('220x220', $e->uri);   
    }else{    
    if(isset($e->field_src_value)&&(!empty($e->field_src_value)))
        {
         $src=image_style_url('220x220', substr($e->field_src_value,21));
        }else{
        $src=image_style_url('220x220', $e->uri);
        }
    }
       # print $src."<hr>";
//$out='<div class="cover"><div class="mask"></div>';
$out='';
 /*   if($e->field_recommended_value)
    {
        $out.='<div class="top_recommended">Рекомендуем</div>';
    }
    */
$title=prep_text($e->title);
/*original
$out.=l('<img class="poster" src="'.$src.'" alt="'.$title.'" title="'.$title.'">','node/'.$e->nid,array('html'=>true,'title'=>$title));

*/

$out.=l(($e->field_tour_value?'<h4>ТУР</h4>':'').'<img class="cover" src="'.$src.'" alt="'.$title.'" title="'.$title.'" />
    <h5>'.$title.'</h5>','node/'.$e->nid,
        array('html'=>true,'attributes'=>array('onclick'=>'if(jQuery(this).attr("class")=="current")return true;else return false;')));


return $out;
}
function _front_draw_city_menu()
{
    
#$current_city =advert_compromise_get_citydomain($_SERVER['HTTP_HOST']);
   
$current_city=$this->get_city_by_url();
#pre($current_city);
$vid=6;

#$citys=db_select("citydomain","c")->fi1elds("c")->orderby('c.name')->execute();
$cities=$this->cities_list();

$out='<div class="citydomain">';

$out.='<div class="current_city">'.(($current_city)?$current_city['name']."&nbsp;":"ВСЯ УКРАИНА&nbsp;").'<span onClick="if(jQuery(\'#citymenu\').is(\':hidden\'))jQuery(\'#citymenu\').show();else jQuery(\'#citymenu\').hide();" class="citydomain_lnk arrow">&nbsp;</span></div>';
#}

$out.='<ul id="citymenu" '.($hidden?' style="display:none;"':'').'>';
#<select onchange="alert(this.value);">';
if($current_city!=false)$out.='<li>'.l('ВСЯ УКРАИНА','http://www.infopark.ua').'</li>';
//while($city=$citys->fetchAssoc())
$c=0;
foreach($cities as $city)
  {
  if($city->tid!=$current_city['tid'])  
  $out.='<li'.(($c>3)?' class="hidden_city" style="display:none;"':'').'>'.l($city->name,$city->url).'</li>';
  
  $c++;
  }
  $out.='</ul>
  <div onclick="jQuery(\'.hidden_city\').show();jQuery(this).hide();" class="cal_btn_clear">Ещё</div>
  </div>';
return $out;  
}
function _spec_event_place($args,$full=false)
{
    global $conf;

extract($args);
$t=strtotime($e->field_schedule_start_value);

$time = substr($e->field_schedule_start_value, 10, 6); 
$date=date('d',$t).' '.$conf['month_names'][date('n',$t)-1]
.' / '.$conf['week_days_short'][date('w',$t)];
if(isset($e->field_src_value)&&(!empty($e->field_src_value)))
{
 $src=image_style_url('w220', substr($e->field_src_value,21));
}else{
$src=image_style_url('w220', $e->uri);
}
$sep_date=implode('</th><div class="lnk_place_month">',explode(' ',$this->draw_dm($e->field_schedule_start_value)));

if($full)
$out.='<div class="lnk'.$e->nid.' lnk_place'.(($e->field_recommended_value)?' recommend_row':'').'">
    <table><tr>      
    <td class="lnk_place_time">'.l($this->draw_event_time($t),'events',array('html'=>true,'attributes'=>array('rel'=>'nofollow'),'query'=>array('date'=>date('dmY',strtotime($e->field_schedule_start_value))))).'</td>
        <td class="lnk_place_info">
<div class="lnk_place_title">'.l($e->title,'node/'.$e->nid,array('attributes'=>array('title'=>_spec_event_prepare_text($e->field_event_description_value)),'query'=>array('evt'=>$e->entity_id))).'</div>
<div class="lnk_place_price">'.l($e->field_schedule_price_value,'node/'.$e->nid,array('html'=>true,'attributes'=>array('rel'=>'nofollow'))).'</div>
        </td>
<td class="lnk_place_buyticket">'.(($e->field_event_buy_a_ticket_value)?'<div class="order_tickets_but"><span>'.l('Купить Билет','node/'.$e->nid,array('html'=>true,'attributes'=>array('rel'=>'nofollow'))).'</span></div>':'').'</td></tr></table></div>';    
else
$out.='<div class="lnk'.$e->nid.' lnk_place'.(($e->field_recommended_value)?' recommend_row':'').'">
    <table border=1><tr>
    <td class="lnk_place_time">'.$this->draw_event_time($t,false).'</td>
    <!--th class="lnk_place_day">'.$sep_date.',</th>
    <th class="lnk_place_wday">'.$conf['week_days_short'][date('N',$t)-1].'</th-->
    <td class="lnk_place_title" style="width:100%">'.l($e->title,'node/'.$e->nid,array('attributes'=>array('title'=>_spec_event_prepare_text($e->field_event_description_value)))).'</td></tr></table></div>';
return $out;
}
function draw_tours()
{
      
//$cc=$this->get_city_by_url();
//$current_city=$cc['tid'];
$query = db_select('node', 'n');	
		$query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		//$query->leftJoin('field_data_field_src', 'src', 'n.nid = src.entity_id');
		
		//$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		//$query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
		$query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
		//$query->leftJoin('taxonomy_index', 'ti', 'event_node.nid = ti.nid');
		//$query->leftJoin('field_data_field_event_buy_a_ticket', 'buy_ticket', 'event_node.nid = buy_ticket.entity_id');
                
               // $query->leftJoin('field_data_field_recommended', 'recom', 'event_node.nid = recom.entity_id');
                
              //  if($statuses['top']) $query->leftJoin('field_data_field_top', 'top', 'event_node.nid = top.entity_id');
               $query->leftJoin('field_data_field_tour', 'tour', 'event_node.nid = tour.entity_id');
                  
		//$query->leftJoin('field_data_field_event_ticket_id', 'ticket_id', 'event_node.nid = ticket_id.entity_id');
		//$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
	#	$query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', event_node.nid)");

		$query->fields('event_node', array('title', 'nid','status'))

			//->fields('s_start', array('field_schedule_start_value'))
			->fields('f', array('uri'))
			//->fields('s_event',array('entity_id'))
			//->fields('place_city', array('field_place_city_tid'))
			//->fields('s_place', array('field_schedule_place_nid'))
			//->fields('src', array('field_src_value'))
			//->fields('place_node', array('title'))
			//->fields('buy_ticket', array('field_event_buy_a_ticket_value'))
                       // ->fields('recom', array('field_recommended_value'))
			//->fields('ticket_id', array('field_event_ticket_id_value'))
			//->fields('event_desc',array('field_event_description_value'))
                        ->fields('tour',array('field_tour_value'));
			#->fields('ti', array('tid'));

			#->groupBy('title')
			#$query->groupBy('s_start.field_schedule_start_value');
			//$query->groupBy('place_node.title');
			//$query->groupBy('s_start.field_schedule_start_value');
                        $query->groupBy('event_node.nid');
			$query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC')
			//->orderBy('recom.field_recommended_value', 'DESC')
                        #->orderBy('(ti.tid=111)', 'DESC')
			->orderBy('s_start.field_schedule_start_value', 'ASC')
			->condition('n.type', 'schedule');
			$query->condition('event_node.status', 1);
			
			$query->condition('event_node.type', 'event');
		//	if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
			
			//if($tids)$query->condition('ti.tid',$tids,'IN');
			//if($statuses['recommended'])$query->condition('recom.field_recommended_value',1);
                        //if($statuses['byticket'])$query->condition('buy_ticket.field_event_buy_a_ticket_value',1);
                        
                       $query->condition('tour.field_tour_value',1);
                     
                   #     
			//$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') IN (:dates)", array(':dates' => $dates));
			$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') >= (:dates)", array(':dates' => date('Ymd')));
			#print ($query);
			#dpm((string) $query);
			#pre($current_city);
                        $query->range(0,5);
	$events = $query->execute()->fetchAll();
    $html='<h1 class="tour_header_title">ТУРЫ</h1>
    <div class="tours_right_block">';
    foreach($events as $event)
    {
        $html.=$this->draw_tour_element($event);
    }
   
    $html.=l('Все Туры','events',array('query'=>array('tid'=>'tour')));
    $html.='</div>';
    return $html;
}
function draw_tour_element($event)
{
    $query = db_select('node', 'n');	
		$query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		//$query->leftJoin('field_data_field_src', 'src', 'n.nid = src.entity_id');
		
		$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		$query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
                $query->leftJoin('taxonomy_term_data', 'td', 'place_city.field_place_city_tid = td.tid');
		$query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
		//$query->leftJoin('taxonomy_index', 'ti', 'event_node.nid = ti.nid');
		//$query->leftJoin('field_data_field_event_buy_a_ticket', 'buy_ticket', 'event_node.nid = buy_ticket.entity_id');
                
             //   $query->leftJoin('field_data_field_recommended', 'recom', 'event_node.nid = recom.entity_id');
                
              //  if($statuses['top']) $query->leftJoin('field_data_field_top', 'top', 'event_node.nid = top.entity_id');
              // $query->leftJoin('field_data_field_tour', 'tour', 'event_node.nid = tour.entity_id');
                  
		//$query->leftJoin('field_data_field_event_ticket_id', 'ticket_id', 'event_node.nid = ticket_id.entity_id');
		//$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		//$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		//$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
	#	$query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', event_node.nid)");

		//$query->fields('event_node', array('title', 'nid','status'))

			$query->fields('s_start', array('field_schedule_start_value'));
			//$query->fields('f', array('uri'))
			//->fields('s_event',array('entity_id'))
			$query->fields('place_city', array('field_place_city_tid'));
                       $query->fields('td',array('name'));
			//->fields('s_place', array('field_schedule_place_nid'))
			//->fields('src', array('field_src_value'))
			//->fields('place_node', array('title'))
			//->fields('buy_ticket', array('field_event_buy_a_ticket_value'))
                       // ->fields('recom', array('field_recommended_value'))
			//->fields('ticket_id', array('field_event_ticket_id_value'))
			//->fields('event_desc',array('field_event_description_value'))
                        //->fields('tour',array('field_tour_value'));
			#->fields('ti', array('tid'));

			#->groupBy('title')
			#$query->groupBy('s_start.field_schedule_start_value');
			//$query->groupBy('place_node.title');
			$query->groupBy('s_start.field_schedule_start_value');
                      //  $query->groupBy('event_node.nid');
			$query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC')
			//->orderBy('recom.field_recommended_value', 'DESC')
                        #->orderBy('(ti.tid=111)', 'DESC')
			->orderBy('s_start.field_schedule_start_value', 'ASC')
			->condition('n.type', 'schedule');
			$query->condition('event_node.status', 1);
			
			$query->condition('event_node.type', 'event');
		//	if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
			
			//if($tids)$query->condition('ti.tid',$tids,'IN');
			//if($statuses['recommended'])$query->condition('recom.field_recommended_value',1);
                        //if($statuses['byticket'])$query->condition('buy_ticket.field_event_buy_a_ticket_value',1);
                        
                       //$query->condition('tour.field_tour_value',1);
                     $query->condition('event_node.nid',$event->nid);
                   #     
			//$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') IN (:dates)", array(':dates' => $dates));
			$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') >= (:dates)", array(':dates' => date('Ymd')));
			#print ($query);
			#dpm((string) $query);
			#pre($current_city);
	$events = $query->execute()->fetchAll();
   
    
    $html='<h2>'.l($event->title,'node/'.$event->nid,array('attributes'=>array('title'=>$event->title))).'</h2>';
    $html.= '<div class="thumb"><div class="istour_oftour"></div>'
            .l('<img src="'.image_style_url('large',$event->uri).'" title="'.$event->title.'" alt="'.$event->title.'">','node/'.$event->nid,array('html'=>true,'attributes'=>array('title'=>$event->title)))
            ."</div>";
    foreach($events as $e)
    {
        $html.='<p>'.date('d.m.Y',strtotime($e->field_schedule_start_value)).' ('.$e->name.')</p>';
    }
    return $html;
} 
function video_player($node)
{
    $width=800;
    $height=360;
    $video_url=$node->field_url['und'][0]['value'];
    if(strstr($video_url,'http://www.youtube.com'))
    {
        //youtube
       #pre($video_url);
      $VIDEO_ID=substr($video_url,strrpos($video_url,'v=')+2);
      
       $html='<iframe class="youtube-player" type="text/html" width="'.$width.'" height="'.$height.'" src="http://www.youtube.com/embed/'.$VIDEO_ID.'" allowfullscreen frameborder="0">
</iframe>';
    }elseif(strstr($video_url,'vimeo.com'))
    {
        
   $VIDEO_ID=substr($video_url,strrpos($video_url,'/')+1);
   $html='<iframe src="//player.vimeo.com/video/'.$VIDEO_ID.'" width="'.$width.'" height="'.$height.'" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'; 
    } else{
     #
        $html='Unknow video type: '.$video_url;
    }
    return $html;
}
function video_player_small($video_url,$title)
{
    
    $width=150;
    $height=100;
   
   // $video_url=$node->field_url['und'][0]['value'];
    if(stripos($video_url,'http://www.youtube.com')>-1)
    {
         
          $type='youtube' ;  
        //youtube
       #pre($video_url);
      $VIDEO_ID=substr($video_url,strrpos($video_url,'v=')+2);
      $src='http://img.youtube.com/vi/'.$VIDEO_ID.'/0.jpg';
       $html='<img src="'.$src.'" width="'.$width.'">';
       
   #    $html='<div class="video_thumb">'.$html.'<span></span></div>';
    }elseif(stripos($video_url,'vimeo.com')>-1)
    {
    $type='vimeo' ;  
   $VIDEO_ID=substr($video_url,strrpos($video_url,'/')+1);
   $src=$this->get_vimeo_thumb($VIDEO_ID);
    $html='<img src="'.$src.'" width="'.$width.'" class="vimeo'.$VIDEO_ID.'">';
    $html.='<script>reload_vimeo("vimeo'.$VIDEO_ID.'")</script>';
  # $html='<iframe src="//player.vimeo.com/video/'.$VIDEO_ID.'" width="'.$width.'" height="'.$height.'" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'; 
    } else{
     #
       return 'Unknow video type: '.$video_url;
    }
    $title=str_replace('"','`',str_replace("'","`",$title));
   
    $html='<div class="video_thumb">'.$html.'<span onclick="video_modal(\''.$VIDEO_ID.'\',\''.$type.'\',\''.$title.'\')"></span></div>';

    return $html;
}
function get_vimeo_thumb($VIDEO_ID)
{
    return 'http://vimeo.com/api/v2/video/'.$VIDEO_ID.'.json';
   /*
    if( $curl = curl_init() ) 
		{
        
		curl_setopt($curl, CURLOPT_URL, 'http://vimeo.com/api/v2/video/'.$VIDEO_ID.'.json');
		#curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
		#$curl_setopt($curl, CURLOPT_POST, false);
		#curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
                
		$out = curl_exec($curl);
                die($out);
		curl_close($curl);
		$data=json_decode($out);
               # pre($data);
             # return 'http://vimeo.com/api/v2/video/'.$VIDEO_ID.'.json'."<hr>";
                $src=$data[0]->thumbnail_medium;
                die($src);
               return $src;
               
                }
  */  
}
function draw_video_nodes($nids)
    {
    drupal_add_js('misc/jquery.plugin.min.js');
     drupal_add_js('misc/jquery.timer.min.js');
    $max_videos2display=2;
    if(empty($nids))return false;
    $nids=explode(",",$nids);


    $query = db_select('node', 'n');	
		
		$query->leftJoin('field_revision_field_url', 'video', "video.entity_id=n.nid");

		$query->fields('n', array('title', 'nid','status'))

		->fields('video', array('field_url_value'));
			
                        $query->groupBy('n.nid')
			->condition('n.nid', $nids,'IN')
			->condition('n.type', 'video');
			$query->condition('n.status', 1);
			$query->orderBy('n.nid','DESC');
                        
	$events = $query->execute()->fetchAll();
       $html='';
      $html.='<h5 class="event_videos">Видео <span>('.count($events).')</span></h5>';
        $html.='<div class="video_box video_nodes">';
          if(count($events)>$max_videos2display) $html.='<a class="prev_event_lnk" href="javascript://" onclick="roll_video(\'video_thumbs_list\',\'prev\','.$max_videos2display.')"></a>';
           $html.='<ul class="video_thumbs_list">';
    $i=0;    
    $j=0;
    foreach($events as $e)
        {
        if($i==$max_videos2display){$i=0;$j++;}
                
        $html.='<li class="vidli'.$j.'" '.(($j!=0)?'style="display:none;"':'').'>'.$this->video_player_small($e->field_url_value,$e->title).'</li>';
        
        $i++;
        }
        $html.='</ul>';
             if(count($events)>$max_videos2display)  $html.='<a class="next_event_lnk" href="javascript://" onclick="roll_video(\'video_thumbs_list\',\'next\')" ></a>';
             $html.='</div>';
         if(count($events)>$max_videos2display) $html.='<script>init_scroll_timer(\'video_thumbs_list\','.$max_videos2display.',3000,\'video_nodes\')</script>';
        return $html;
    }
    function draw_additional_images($imgs)
    {
    //    drupal_add_js('misc/jquery.timer.js');
      $max_imgs2display=3; 
        if(count($imgs)==0)return false;
          $html='<div class="video_box additional_images">
            <a class="prev_event_lnk" href="javascript://" onclick="roll_video(\'img_thumbs_list\',\'prev\','.$max_imgs2display.')"></a>
            <ul class="img_thumbs_list">';
    $i=0;    
    $j=0;
   
    foreach($imgs as $e)
        {
        if($i==$max_imgs2display){$i=0;$j++;}
                
        $html.='<li class="vidli'.$j.'" '.(($j!=0)?'style="display:none;"':'').'>'.
               '<a class="fancybox" rel="gallery" href="'.image_style_url('large', $e['uri']).'" title="'.htmlspecialchars($e['title']).'">
                   <img src="'.image_style_url('100_100', $e['uri']).'" /></a>'
                .'</li>';
        
        $i++;
        }
    
     $html.='</ul>
            <a class="next_event_lnk" href="javascript://" onclick="roll_video(\'img_thumbs_list\',\'next\','.$max_imgs2display.')" style="float:right"></a>
            </div>';
  $html.='<script>init_scroll_timer(\'img_thumbs_list\','.$max_imgs2display.',3000,\'additional_images\');</script>';
        return $html;
    }
    function places_ajax_engine($page=0,$width)
    {
       if($width>1910)$size=6; 
       elseif($width>1600)$size=5;
           elseif(($width>1366)&&($width<1600))$size=4;
            else $size=3;
      
       
          
   
        $places=$this->get_places($page,$size);
        if(count($places)==0)return null;
        $html='';
        if($width)
        {
        $html.='<div id="columns">';
        
        foreach($places as $p)
            $html.=$this->draw_place_tile($p);
        $html.='</div>';
        }
        if(!$width)
        {    
       $html.='<div id="places_more_box"></div>';      
      
        $html.='<div class="places_more"><a href="javascript://" onclick="get_more_places();">'._('Ещё').'</a></div>';
        $html.='<script>get_more_places();</script>';
        }
        return $html;
       
    }
    function get_places4category($tid)
    {
     
        $cc=$this->get_city_by_url();
        $current_city=$cc['tid'];
     
      #  $current_city=0;
        $query=db_select('node','n');
                $query->condition('n.type','place')
                ->condition('ti.tid',$tid);
             #   ->condition('top.field_top_value',1)
               if(user_access('administer nodes')==0){
                   $query->condition('n.status',1);
                    #$query->condition('event.status',1);
               }
           $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
            $query->leftJoin('field_data_field_top', 'top', 'top.entity_id=n.nid');
            $query->leftJoin('field_data_field_top_sorting', 'tops', 'tops.entity_id=n.nid');
            $query->leftJoin('field_revision_field_schedule_place', 's_place', 's_place.field_schedule_place_nid=n.nid');
            
            $query->leftJoin('field_data_field_place_city', 'place_city', 'n.nid = place_city.entity_id');
            $query->leftJoin('field_data_field_place_thumbnail', 'nthumbnail', 'n.nid = nthumbnail.entity_id');
             $query->leftJoin('file_managed', 'f', 'nthumbnail.field_place_thumbnail_fid = f.fid');
           # $query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', n.nid)");
            $query->leftJoin('field_data_field_src', 'src', 'src.entity_id = n.nid');
            
            $query->leftJoin('field_data_field_place_phone', 'nphone', 'n.nid = nphone.entity_id');
         #   $query->leftJoin('field_data_field_place_description', 'ndescription', 'n.nid = ndescription.entity_id');
            $query->leftJoin('field_data_field_place_website', 'nwebsite', 'n.nid = nwebsite.entity_id');
            $query->leftJoin('field_data_field_place_address', 'naddress', 'n.nid = naddress.entity_id');

           
            $query->leftJoin('field_revision_field_schedule_start', 's_start', 's_start.entity_id=s_place.entity_id AND '."DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > '".date('Ymd')."'");
             $query->leftJoin('field_revision_field_schedule_event', 's_event', 's_event.entity_id=s_start.entity_id');
            $query->leftJoin('node', 'event', 'event.nid=s_start.entity_id');
            $query->fields('n',array('nid','title'))
            ->fields('top',array('field_top_value'))  
           ->fields('src', array('field_src_value'))
         ->fields('nphone', array('field_place_phone_value'))
       # ->fields('ndescription', array('field_place_description_value'))
        ->fields('nwebsite', array('field_place_website_value'))
        ->fields('naddress', array('field_place_address_value'))
        ->fields('place_city', array('field_place_city_tid'))
        ->fields('f', array('uri'))
        ->fields('place_city',array('field_place_city_tid'))
       # ->fields('ua')
        #->fields('ti')       
                    
            #->fields('s_start',array('field_schedule_start_value')) 
           
            ->orderBy('top.field_top_value','DESC')
            ->orderBy('tops.field_top_sorting_value','DESC')         
            ->orderBy("(DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > ('".date('Ymd')."'))","DESC")        
            ->orderBy('s_start.field_schedule_start_value'); 
          #  ->range(($p*$step),$step);
            $query->groupBy('n.nid');
            $query->addExpression('COUNT(DISTINCT s_event.entity_id)','num_events');
           # $query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
           # $query->where("top.field_top_value=1 OR DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > (:date)", array(':date' => date('Ymd')));
        if($current_city)$query->condition('place_city.field_place_city_tid', $current_city);
        $result=$query->execute();
   
        while($r=$result->fetchObject())
        {
            $data[]=$r;
        }
          #pre($data,1);
      return $data;
    }
    /*
     * GET Places 
     * @param $p=page to display
     */
    function get_places($p,$step)
    {
        if(!is_numeric($p))$p=0;
      $cc=$this->get_city_by_url();
        $current_city=$cc['tid'];
      
      #  $current_city=0;
        $query=db_select('node','n')
                ->condition('n.type','place');
              if(user_access('administer nodes')==0){
                   $query->condition('n.status',1);
                    $query->condition('event.status',1);
               }
            $query->leftJoin('field_data_field_top', 'top', 'top.entity_id=n.nid');
            $query->leftJoin('field_data_field_top_sorting', 'tops', 'tops.entity_id=n.nid');
            $query->leftJoin('field_revision_field_schedule_place', 's_place', 's_place.field_schedule_place_nid=n.nid');
            
            $query->leftJoin('field_data_field_place_city', 'place_city', 'n.nid = place_city.entity_id');
            $query->leftJoin('field_data_field_place_thumbnail', 'nthumbnail', 'n.nid = nthumbnail.entity_id');
             $query->leftJoin('file_managed', 'f', 'nthumbnail.field_place_thumbnail_fid = f.fid');
           # $query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', n.nid)");
            
            $query->leftJoin('field_data_field_place_phone', 'nphone', 'n.nid = nphone.entity_id');
            #$query->leftJoin('field_data_field_place_description', 'ndescription', 'n.nid = ndescription.entity_id');
            $query->leftJoin('field_data_field_place_website', 'nwebsite', 'n.nid = nwebsite.entity_id');
            $query->leftJoin('field_data_field_place_address', 'naddress', 'n.nid = naddress.entity_id');

            
            $query->leftJoin('field_revision_field_schedule_start', 's_start', 's_start.entity_id=s_place.entity_id AND '."DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > '".date('Ymd')."'");
            $query->leftJoin('field_revision_field_schedule_event', 's_event', 's_event.entity_id=s_start.entity_id');
            $query->leftJoin('node', 'event', 'event.nid=s_event.entity_id');
            $query->fields('n',array('nid','title'))
            ->fields('top',array('field_top_value')) 
             ->fields('tops',array('field_top_sorting_value')) 
           
         ->fields('nphone', array('field_place_phone_value'))
      #  ->fields('ndescription', array('field_place_description_value'))
        ->fields('nwebsite', array('field_place_website_value'))
        ->fields('naddress', array('field_place_address_value'))
        ->fields('place_city', array('field_place_city_tid'))
        ->fields('f', array('uri'))
        ->fields('place_city',array('field_place_city_tid'))
       # ->fields('ua')
        #->fields('ti')       
                    
            #->fields('s_start',array('field_schedule_start_value'))  
                   ->orderBy('top.field_top_value','DESC')
                  //  ->orderBy('(tops.field_top_sorting_value!=NULL)','DESC') 
                       ->orderBy('tops.field_top_sorting_value','DESC')  
                   
            ->orderBy("(DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > ('".date('Ymd')."'))","DESC")        
            ->orderBy('s_start.field_schedule_start_value') 
            ->range(($p*$step),$step);
            $query->groupBy('n.nid');
            $query->addExpression("COUNT(DISTINCT s_event.entity_id)","num_events");
          #  $query->addExpression("if(DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > '".date('Ymd')."',COUNT(DISTINCT s_start.field_schedule_start_value),0) ",'num_events');
         # $query->addExpression("LENGTH(tops.field_top_sorting_value)","sorting_value");
         #(DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > ('".date('Ymd')."')   
         #   
           # $query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
        #    $query->where("top.field_top_value=1 OR DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > (:date)", array(':date' => date('Ymd')));
        if($current_city)$query->condition('place_city.field_place_city_tid', $current_city);
        $result=$query->execute();
    
        while($r=$result->fetchObject())
        {
            $data[]=$r;
        }
       #pre($data);
      return $data;
    }
    function draw_place_tile($p)
    {
        $city_tid=$this->get_city_tid();
       /*$cc=$this->get_city_by_url();
        $current_city=$cc['tid'];*/
      # pre($p);
      # die($p->field_place_city_tid);
        $html='<div class="pin">';
            
         
   
   if (isset($p->uri)){ 
      $thumb_html.='<div class="thumb"><img src="'.image_style_url('w220', $p->uri).'" /></div>';
    }else{ 
	$thumb_html.='<div class="thumb'.(($p->num_events)?' place_with_event':'').'"></div>';
    }
    $html.=l($thumb_html, 'node/' . $p->nid,array('html'=>true,'attributes'=>array('title'=>$p->title)));
  
    if($p->num_events) $html.='<div class="afishes_count">'.$p->num_events.'</div>';
     $html.='<div class="info">
	<h2>'.l($p->title, 'node/' . $p->nid,array('attributes'=>array('title'=>$p->title))).'</h2>   
	<table class="short_info">';
     if($city_tid==0)
     {
	$html.='<tr><td class="short_info_label"><div class="icon city"></div></td>
            <td>
              <a href="'.get_city_url_by_id($p->field_place_city_tid).'" title="'.$this->cities_list[$p->field_place_city_tid]->name.' Инфопарк" class="city_link"> '.$this->cities_list[$p->field_place_city_tid]->name.'</a>
             </td>
        </tr>';
     }
        if ($p->field_place_address_value)
        {
       $html.='<tr><td class="short_info_label"></td><td>';
       $html.=nl2br($p->field_place_address_value);
       $html.='</td></tr>';
        }
        if ($p->field_place_phone_value) 
        {    
	$html.='<tr><td><div class="icon phone"></div></td><td>';
        $html.=$p->field_place_phone_value;
	$html.='</td></tr>';
        }
        $html.='</table>
</div>';            
	$html.='</div>';
       # print "<pre>";
        #die(htmlspecialchars($html));
        return $html;
    }
    function frontpage_places_top()
    {
     
      $cc=$this->get_city_by_url();
        $current_city=$cc['tid'];
       // $step=3;
      #  $current_city=0;
        $query=db_select('node','n')
                ->condition('n.type','place');
                 $query->condition('n.status',1);
                 $query->condition('top.field_top_value',1);
                 /*
              if(user_access('administer nodes')==0){
                   $query->condition('n.status',1);
                 //   $query->condition('event.status',1);
               }*/
            $query->leftJoin('field_data_field_top', 'top', 'top.entity_id=n.nid');
            $query->leftJoin('field_revision_field_schedule_place', 's_place', 's_place.field_schedule_place_nid=n.nid');
            
            $query->leftJoin('field_data_field_place_city', 'place_city', 'n.nid = place_city.entity_id');
            $query->leftJoin('field_data_field_place_thumbnail', 'nthumbnail', 'n.nid = nthumbnail.entity_id');
             $query->leftJoin('file_managed', 'f', 'nthumbnail.field_place_thumbnail_fid = f.fid');
          
            
            $query->leftJoin('field_data_field_place_phone', 'nphone', 'n.nid = nphone.entity_id');
          
            $query->leftJoin('field_data_field_place_website', 'nwebsite', 'n.nid = nwebsite.entity_id');
            $query->leftJoin('field_data_field_place_address', 'naddress', 'n.nid = naddress.entity_id');

            
            $query->leftJoin('field_revision_field_schedule_start', 's_start', 's_start.entity_id=s_place.entity_id AND '."DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > '".date('Ymd')."'");
            $query->leftJoin('field_revision_field_schedule_event', 's_event', 's_event.entity_id=s_start.entity_id');
            $query->leftJoin('node', 'event', 'event.nid=s_event.entity_id');
            $query->fields('n',array('nid','title'))
            ->fields('top',array('field_top_value'))  
           
         ->fields('nphone', array('field_place_phone_value'))
     
        ->fields('nwebsite', array('field_place_website_value'))
        ->fields('naddress', array('field_place_address_value'))
        ->fields('place_city', array('field_place_city_tid'))
        ->fields('f', array('uri'))
        ->fields('place_city',array('field_place_city_tid'))
     
            
            ->orderBy("(DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > ('".date('Ymd')."'))","DESC")        
            ->orderBy('s_start.field_schedule_start_value'); 
        
            $query->groupBy('n.nid');
          #  $query->addExpression("if(DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > '".date('Ymd')."',COUNT(DISTINCT s_start.field_schedule_start_value),0) ",'num_events');
          $query->addExpression("COUNT(DISTINCT s_event.entity_id)","num_events");
         #(DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > ('".date('Ymd')."')   
         #   
           # $query->addExpression('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')');
        #    $query->where("top.field_top_value=1 OR DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') > (:date)", array(':date' => date('Ymd')));
        if($current_city)$query->condition('place_city.field_place_city_tid', $current_city);
        $result=$query->execute();
        $out='<div id="column" class="front-places">';
        while($r=$result->fetchObject())
        {
            $out.=$this->draw_place_tile($r);
        #    $data[]=$r;
        }
        $out.='</div>';
        #$out.='<a class="bigmore" href="/events">Смотреть все афиши</a>';
        $out.=l('Смотреть все места','places',array('attributes'=>array('class'=>array('bigmore'))));
      return $out;
    }
    /*Called from block--spec_event_places--block_event_places.tpl.php*/
    function draw_event_ticket($th,$buy_ticket=0)
    {
     
      $html='<div class="od schedule'.$th->entity_id.'" onMouseOver="hightlight_thumb('.$th->entity_id.');hightlight_ticket('.$th->entity_id.');">
                                    <div class="od_left_right">
                                <div class="od_left">
                                    <div class="lidate"><a href="/events?day='.date('dmY',strtotime($th->field_schedule_start_value)).'">';
                                
    $html.=$this->draw_event_time(strtotime($th->field_schedule_start_value));
       $html.= '</a></div></div>';

   $html.= '</div>
   <div class="od_right">
           <div class="od_place"><h4>'.l($th->title,'node/'.$th->field_schedule_place_nid).'</h4>
                   <div class="city">'.$th->name.'</div>
           </div>';
			
        if($th->field_schedule_end_value)
        {
            if(date('d',strtotime($th->field_schedule_start_value))!=date('d',strtotime($th->field_schedule_end_value)))
            {
            $html.= '<div class="od_tm">Окончание '.date('j ',strtotime($th->field_schedule_end_value)).$conf['month_namez'][date('n',strtotime($th->field_schedule_end_value))-1];
            $html.=" ".date('H:i',strtotime($th->field_schedule_end_value))."</div>";
            }else{
            $html.= '<div class="od_tm">Окончание '.date('H:i',strtotime($th->field_schedule_end_value)).'</div>';

            }
        }
	if(!empty($th->field_schedule_price_value))$html.='<div class="price">Цена: '.$th->field_schedule_price_value.'</div>';
		
	$html.='</div></div>';                 
		
	if(($buy_ticket)&&(strtotime($th->field_schedule_start_value)>time()))
        {
         $html.='<div class="order_tickets_lnk" onclick="_gaq.push([\'_trackEvent\', \'buy_ticket\', \'main_buy_button\',\'choose_how_to_buy\']);order_ticket_form(\''.$th->entity_id.'\')">
                    <span> Купить билет</span>
                 </div>';
        }                 
	 $html.='</div>';
         return $html;
        
    }
    /*Generator meta tags*/
    function seo_meta_generator()
    {
    global $conf;
    $city=$this->get_city_by_url();
    $city_string=(($city['current_city_name'] != "")?' '.$city['current_city_name']:"");   
    $city_string_a=(($city['current_city_name'] != "")?' '.$city['current_city_name'].'а':"");  
    $city_string_e=(($city['current_city_name'] != "")?' '.$city['current_city_name'].'е':"");
    $html='';
   if(arg(0)=='node')
        {

        $node=node_load(array('nid'=>arg(1)));
        $results = db_query('SELECT td.* '
                . 'FROM {taxonomy_index} ti '
                 . 'LEFT JOIN {taxonomy_term_data} td ON td.tid=ti.tid '
                . 'WHERE ti.nid = :nid', array(':nid' => $node->nid));
            foreach ($results as $result) {
              $terms[] = $result;
            }
         #   pre($terms,1);
        switch($node->type)
                {
                case 'event':
                 
                    $places=$this->get_place_by_event2($node->nid);
                  # pre($places,1);
                    foreach($places as $p){
                        $pl[]=$p->title." в ".$p->name;
                     
                    }
                    
                    $pl=array_unique($pl);
               
                  
                    $title=$node->title.' , '.$node->title.'  смотреть, '.$node->title.'  фото - все события на сайте Афиша | Инфопарк афиша '  
                            .$city_string;
                   # pre($terms,1);
                    $description=substr($this->pq(strip_tags($node->field_event_description['und'][0]['value'])),0,256);
                    $keywords[]=$this->pq($node->title);
                    if($node->field_event_buy_a_ticket['und'][0]['value'])
                    {
                         $keywords[]='купить билет'; 
                    }
                    foreach($terms as $term)
                        { 
                        $keywords[]=$this->pq($term->name); 
                       # $keywords[]=prep_text($node->title)." - ".prep_text($term->name);
                        if(!empty($term->meta_keywords))$keywords[]=$term->meta_keywords;
                        }
                    
                    foreach($pl as $p)
                        {
                        $keywords[]=$this->pq($p);
                        }
                  
                    $keywords[]=$this->pq($node->title).' цены';
                    $keywords[]=$this->pq($node->title).' смотреть';
                    $keywords[]=$this->pq($node->title).' фото';
                    $keywords[]=$this->pq($node->title).' читать';
                    $keywords[]=$this->pq($node->title).' афиша';
                    #    pre($keywords,1);   
                break;
                case 'place':
                  
                    $title=$node->title.':  '.$node->title.' найти, '.$node->title.' программа, '.$node->title
                    .' адрес - вся информация на портале Афиша | Инфопарк афиша'
                    .$city_string_a
                    .' Билеты на концерты.';
                    if(!empty($node->meta_description['und'][0]['metatags_quick']))
                    {
                        $description=$this->pq($node->meta_description['und'][0]['metatags_quick']);
                    }else{
                    $description=$this->pq($node->title).' одно из самых интересных мест '
                     .$city_string_a
                        .', где можно хорошо провести время. На сайте Афиша Вы всегда найдете свежую информацию и программу '.prep_text($node->title);
                    }
                    if(!empty($node->meta_keywords['und'][0]['metatags_quick']))
                    {
                        $keywords[]=$this->pq($node->meta_keywords['und'][0]['metatags_quick']);
                    }else{
                    $keywords[]=$this->pq($node->title);
                     foreach($terms as $term)
                         { 
                         $keywords[]=$this->pq($term->name);
                       #  $keywords[]=$this->pq(($node->title)." - ".$this->pq(($term->name);
                          if(!empty($term->meta_keywords))$keywords[]=$this->pq($term->meta_keywords);
                         }
                    $keywords[]=$this->pq($node->title).' найти';
                    $keywords[]=$this->pq($node->title).' программа';
                    $keywords[]=$this->pq($node->title).' адрес';
                    $keywords[]=$this->pq($node->title).' афиша';
                    }
                      #
                break;
                case 'newarticle':
                        $title=$node->title.' '.$city_string_e.'| Инфопарк афиша '
                        .$city_string_a. ' Билеты на концерты.';
                        $description="На портале Афиша -".prep_text($node->title)." "
                                .prep_text(mb_substr(strip_tags($node->body['und'][0]['value']),0,255)).'..., '
                                .$city_string;
                        $keywords[]=prep_text($node->title);
                        $keywords[]=prep_text($node->title)."  ".$city_string.' читать';
                        $keywords[]=prep_text($node->title).$city_string.' искать';
                        $keywords[]=prep_text($node->title).$city_string.' найти';
                        $keywords[]=prep_text($node->title).$city_string.' смотреть';
                       
                break;
                case 'media_gallery':
                        $month_name=$conf['month_namez'][(int)date('m',$node->created)-1];
                        
                        $title=prep_text($node->title).', '.prep_text($node->title).' фото, вечеринка '.prep_text($node->title)
                                .' фото | Инфопарк афиша'.$city_string_a.' Билеты на концерты.';
                        
                        $description=prep_text($node->title).' - галерея нашего портала с фото, где Вы можете посмотреть фото с концерта или свадьбы, вечеринки или party.';
                        $keywords[]=prep_text($node->title).' галерея '.prep_text($month_name);
                        $keywords[]='галерея '.prep_text($node->title);
                        $keywords[]='вечеринка '.prep_text($node->title).' галерея';
                        $keywords[]='выступление '.prep_text($node->title).' галерея';
                        $keywords[]='party '.prep_text($node->title).' галерея';
                        
                break;
                case 'page':
                   
                        switch($node->nid)
                        {
                            case 57:
                              //events
                               if($_GET['tid'])$_GET['category']=$_GET['tid'];
                                if(isset($_GET['category']))
                                {
                                       ### EVENTS SOME CATEGORY ###
                                        #$term=taxonomy_term_load($_GET['category']);
                                     #   print $_GET['category']."<hr>";
                                     $tt = db_select('taxonomy_term_data','td');
                                                 $tt->fields('td',array('name','meta_keywords'));
                                                 $tt->condition('td.tid',$_GET['category']);
                                                  $rez=$tt->execute();
                                                  $term=$rez->fetchObject();
                                                  
                                                
                                         
                                            #pre($t,1);
                                        $title=prep_text($term->name).' '.$city_string_a.' : '.$term->name." ".$city_string_a." афиша, ".$term->name." "
                                                .$city_string_a." смотреть список, ".$term->name." ".$city_string_a."  выбрать, "
                                                .$term->name." ".$city_string_a." найти | Инфопарк афиша ".$city_string.". Билеты на концерты";
                                        $description="На нашем портале лучшие ".prep_text($term->name)." ".$city_string_a
                                                ." Афиша позволит Вам найти любимый фильм, адрес, заказать билеты, узнать время сеансов";
                                        if(!empty($term->meta_keywords))
                                        {
                                           $keywords[]=$term->meta_keywords;    
                                      #     $keywords[]=$term->name." ".$city_string_a." афиша";
                                        }else{
                                        $keywords[]=$term->name." ".$city_string_a;
                                        $keywords[]=$term->name." ".$city_string_a." афиша";
                                        $keywords[]=$term->name." ".$city_string_a." смотреть";
                                        $keywords[]=$term->name." ".$city_string_a." найти  фильм";
                                        $keywords[]=$term->name." ".$city_string_a." заказать билеты";
                                        }
                                }else{
                                    ### EVENTS ALL ###
                                $title="Афиша: события, концерты, спектакли, галереи | Инфопарк афиша".$city_string_a." Билеты на концерты.";
                                $description="Наша афиша позволит узнать Вам самые свежие новости о концертах, спектаклях и выставках Ваших любимых артистов, музыкантов, художников.";
                                
                                $keywords[]="Афиша";
                                $keywords[]="события";
                                $keywords[]="концерты";
                                $keywords[]="спектакли";
                                $keywords[]="галереи";
                                $keywords[]="новости искусства";
                                    
                                }      
                            break;
                            case 4435:
                              //places
                                #if($_GET['tid'])$_GET['category']=$_GET['tid'];
                                #die($_GET['category']);
                                if($_GET['category'])
                                        {
                                       # $term=taxonomy_term_load($_GET['category']);
                                    $tt = db_select('taxonomy_term_data','td');
                                                 $tt->fields('td',array('name','meta_keywords'));
                                                 $tt->condition('td.tid',$_GET['category']);
                                                  $rez=$tt->execute();
                                                  $term=$rez->fetchObject();
                                        $title=$this->pq($term->name).' '.$city_string_a.' : '.$term->name." ".$city_string_a." афиша, ".$term->name." "
                                                .$city_string_a." смотреть список, ".$term->name." ".$city_string_a."  выбрать, "
                                                .$term->name." ".$city_string_a." найти | Инфопарк афиша ".$city_string.". Билеты на концерты";
                                        $description="На нашем портале лучшие ".prep_text($term->name)." ".$city_string_a
                                                ." Афиша позволит Вам найти любимый фильм, адрес, заказать билеты, узнать время сеансов";
                                        if(!empty($term->meta_keywords))
                                        {
                                           $keywords[]=$term->meta_keywords;    
                                        #   $keywords[]=$term->name." ".$city_string_a." афиша";
                                        }else{
                                        $keywords[]=$term->name." ".$city_string_a;
                                        $keywords[]=$term->name." ".$city_string_a." афиша";
                                        $keywords[]=$term->name." ".$city_string_a." смотреть";
                                        $keywords[]=$term->name." ".$city_string_a." найти  фильм";
                                        $keywords[]=$term->name." ".$city_string_a." заказать билеты";
                                        }
                                        }else{
                                
                                $title='Главные места, где мы рекомендуем Вам побывать, посетить главные места | Инфопарк афиша'.$city_string_a.". Билеты на концерты.";
                                $description="Главные места, где мы рекомендуем Вам побывать: на нашем сайте всегда представлены самые модные и популярные клубы, кафе, бары и рестораны ".$city_string_a;
                                $keywords[]="Главные места";
                                $keywords[]="главные места клубы";
                                $keywords[]="главные места кафе";
                                $keywords[]="главные места бары";
                                $keywords[]="главные места суши-бары";
                                $keywords[]="главные места развлекательные центры";
                              
                                        }    
                            break;
                            default:
                             ### HOME PAGE ###    
                                $title="Афиша: события, концерты, спектакли, галереи | Инфопарк афиша".$city_string_a." Билеты на концерты.";
                                $description="Наша афиша позволит узнать Вам самые свежие новости о концертах, спектаклях и выставках Ваших любимых артистов, музыкантов, художников.";
                                $keywords[]="Афиша";
                                $keywords[]="события";
                                $keywords[]="концерты";
                                $keywords[]="спектакли";
                                $keywords[]="галереи";
                                $keywords[]="новости искусства";
                            
                            
                        }
                       
                break;
                default:
                        $title="Афиша: события, концерты, спектакли, галереи | Инфопарк афиша".$city_string_a." Билеты на концерты.";
                        $description="Наша афиша позволит узнать Вам самые свежие новости о концертах, спектаклях и выставках Ваших любимых артистов, музыкантов, художников.";
                        $keywords[]="Афиша, события, концерты, спектакли, галереи, новости искусства";
                        
                }
            }elseif((arg(0)=='events')&&(arg(1)=='engine')){
                $title="Афиша: события, концерты, спектакли, галереи | Инфопарк афиша".$city_string_a." Билеты на концерты.";
                $description="Наша афиша позволит узнать Вам самые свежие новости о концертах, спектаклях и выставках Ваших любимых артистов, музыкантов, художников.";
		$keywords[]="Афиша";
                $keywords[]="события";
                $keywords[]="концерты";
                $keywords[]="спектакли";
                $keywords[]="галереи";
                $keywords[]="новости искусства";

    }elseif((arg(0)=='taxonomy')&&(arg(1)=='term')&&(arg(2)==69)){
                $title="Галереи: свадьба, party, вечеринка, session, выступление в клубах ".$city_string_a." | Инфопарк афиша"
                        .$city_string_a." Билеты на концерты.";
		$description="Галереи-раздел нашего портала с фото, где Вы можете посмотреть фото со свадьбы, вечеринки или party.";
		$keywords[]="Галереи";
                $keywords[]="свадьба фото";
                $keywords[]="вечеринка фото";
                $keywords[]="выступление фото";
                $keywords[]="party фото";

    }elseif((arg(0)=='gallery_period')){

#Галереи апрель: свадьба в Малиновке, party Ekipash, вечеринка Beautiful Night в клубах Харькова
                $month_name=$conf['month_namez'][((int)substr(arg(1),0,2))-1];
                $title="Галереи ".strtolower($month_name)." в клубах ".$city_string_a." | Инфопарк афиша"
                     .$city_string_a." Билеты на концерты.";
		$description="Галереи-".strtolower($month_name)." информационный подраздел нашего портала с фото, где Вы можете посмотреть фото со свадьбы, вечеринки или party.";
		$keywords[]="Галерея фото ".strtolower($month_name);
                $keywords[]="свадьба фото ".strtolower($month_name);
                $keywords[]="вечеринка фото ".$month_name;
                $keywords[]="выступление фото ".strtolower($month_name);
                $keywords[]="party фото ".strtolower($month_name);

           }elseif(arg(0)=='news'){

                if(arg(1)>0)
                {
                $month_name=strtolower($conf['month_namez'][((int)substr(arg(1),4,2))-1]);
                                $title="Новости архив ".$month_name.", список новостей архив ".$month_name.", новости портала архив ".$month_name."| Инфопарк афиша"
                                        .$city_string_a." Билеты на концерты.";
                                $description="Список новостей - архив портала ".$month_name." ".substr(arg(1),0,4).".  События и новости на портале Афиша за ".$month_name." ".substr(arg(1),0,4);
                                $keywords[]="Новости архив ".$month_name;
                                $keywords[]="список новостей архив ".$month_name;
                                $keywords[]="новости портала архив ".$month_name;

                }else{
                                $title="Список новостей: портал новостей, архив новостей | Инфопарк афиша ".$city_string_a." Билеты на концерты.";
                                $description="Список новостей: все новости из мира развлечений, как провести время, как найти мероприятие ";
                                $keywords[]="Список новостей";
                                $keywords[]="список новостей смотреть в ".$city_string_e;
                                $keywords[]="список новостей найти в ".$city_string_e;
                                $keywords[]="список новостей читать в ".$city_string_e;

                }
            }elseif((arg(0)=='media-gallery')&&(arg(1)=='detail')){
                $node=node_load(arg(2));
                $title=$node->title.", ".$node->title." фото";
		$description=prep_text($node->title)." - галерея нашего портала с фото, где Вы можете посмотреть фото с концерта или свадьбы, вечеринки или party.";
		$keywords[]=prep_text($node->title)." фото вечеринка";
                $keywords[]=prep_text($node->title);
                $keywords[]="вечеринка ".prep_text($node->title)." фото";
                $keywords[]="выступление ".prep_text($node->title)." фото";
                $keywords[]="party ".prep_text($node->title)." фото";

                 }else{
                $title="Инфопарк афиша ".$city_string_a." Билеты на концерты.";
                $description="Продажа билетов на развлекательные мероприятия. Спектакли, концерты, шоу,ночные клубы, развлечение, ".$city_string_a;
                $keywords[]='Инфопарк';
                $keywords[]='афиша';
                $keywords[]='Билеты';
                 }
       
    return '<title>'.$title.'</title>
		<meta name="description" content="'.$description.'">
		<meta name="keywords" content="'.implode(", ",$keywords).'">';

    }
    function pq($str)
    {
        return str_replace('"',"&quot;",$str);
    }
}
?>